﻿var _lists = new Array();
var _bindings = new Array();

var responseResult  = "Resultado";
var responseValue   = "Valor";
var responseMessage = "Mensaje";

var SelectListHelper = new Object();
    SelectListHelper.loadSelectList                         = _loadSelectList;
    SelectListHelper.fillSelectList                         = _fillSelectList;
    SelectListHelper.fillSelectListExtended                 = _fillSelectListExtended;
    SelectListHelper.formatForSelectList                    = _formatForSelectList;
    SelectListHelper.getDataFromSelectList                  = _getDataFromSelectList;
    SelectListHelper.getDataFromList                        = _getDataFromList;
    SelectListHelper.disableOptionsFromSelectList           = _disableOptionsFromSelectList;
    SelectListHelper.findOptionByText                       = _findOptionByText;
    SelectListHelper.findOptionByValue                      = _findOptionByValue;
    SelectListHelper.getSelectedValueFromSelectList         = _getSelectedValueFromSelectList;
    SelectListHelper.getSelectedTextFromSelectList          = _getSelectedTextFromSelectList;
    SelectListHelper.getSelectLists                         = _getSelectLists;
    SelectListHelper.getSelectList                          = _getSelectList;
    SelectListHelper.bindListOnChangeEvent                  = _bindListOnChangeEvent;
    SelectListHelper.setBindings                            = _setBindings;
    SelectListHelper.getBindings                            = _getBindings;
    SelectListHelper.setSelectListBasedOnSelection          = _setSelectListBasedOnSelection;
    SelectListHelper.setSelectListBasedOnSelectionBindings  = _setSelectListBasedOnSelectionBindings;
    SelectListHelper.setSelectedValue                       = _setSelectedValue;
    SelectListHelper.setSelectedIndex                       = _setSelectedIndex;
    SelectListHelper.removeOption                           = _removeOption;
    SelectListHelper.removeAllOptions                       = _removeAllOptions;
    SelectListHelper.appendOption                           = _appendOption;
    SelectListHelper.copyItems                              = _copyItems;

function _fillSelectList(selectListId, data, group, removeExisting)
{
    var selectList = $("#" + selectListId);

    if ( removeExisting == true )
        _removeAllOptions(selectListId);

    if ( data.length == 0 )
        return;

    var items = "";
    var options = data.split(';');
    for (var i = 0; i < options.length; i++)
    {
        var option = options[i].split(':');
        items += '<option value=' + option[0] + '>' + option[1] + '</option>';
    }
    if ( !isEmpty(group) )
    {
        var groupItems = items;
        items = '<optgroup label="' + group + '" >' + groupItems + '</optgroup>';
    }
    
    selectList.append(items);
}
function _fillSelectListExtended(selectListId, list, valueProperty, textProperty, enabledProperty, group, removeExisting)
{
    var selectList = $("#" + selectListId);

    if ( isEmpty(list) )
        return;

    if ( removeExisting == true )
        _removeAllOptions(selectListId);

    var _valueProperty      = "Value";
    var _textProperty       = "Text";
    var _enabledProperty    = "Enabled";
    if ( !isEmpty(valueProperty) )
        _valueProperty = valueProperty;
    if ( !isEmpty(textProperty) )
        _textProperty = textProperty;
    if ( !isEmpty(enabledProperty) )
        _enabledProperty = enabledProperty;

    var items = "";
    for (var i = 0; i < list.length; i++)
    {
        value       = list[i][_valueProperty];
        text        = list[i][_textProperty];
        enabled     = list[i][_enabledProperty];
        items += "<option value='" + value + "' " + (enabled ? "" : "disabled") + " >" + text + "</option>";
    }

    if ( !isEmpty(group) )
    {
        var groupItems = items;
        items = '<optgroup label="' + group + '" >' + groupItems + '</optgroup>';
    }
    selectList.append(items);
}
function _formatForSelectList(list, valueProperty, nameProperty)
{
    var selectList = "";
    var value, text;
    if ( !isEmpty(list) )
    {
        for (var i = 0; i < list.length; i++)
        {
            //if object's Value & Name property names were specified..
            if (valueProperty && nameProperty)
            {
                value = list[i][valueProperty];
                text = list[i][nameProperty];
            }
            else
            {
                //else, use defaults ("Value" and "text")..
                value = list[i].Value;
                text = list[i].Text;
            }

            if (selectList.length == 0)
                selectList = value + ":" + text;
            else
                selectList += ";" + value + ":" + text;
        }
    }
    return selectList;
}
function _getDataFromSelectList(selectListId, copyTextAsValue)
{
    var list = "";
    $("#" + selectListId + " > option").each
    (
        function ()
        {
            var text = this.text;
            var value = this.value;

            if (copyTextAsValue != undefined && copyTextAsValue == true)
                value = text;

            if (list.length == 0)
                list = value + ":" + text;
            else
                list += ";" + value + ":" + text;
        }
    );
    return list;
}
function _getDataFromList(selectList, copyTextAsValue)
{
    var list = "";
    if ( selectList.length > 0 )
    {
        for (var i=0; i < selectList.length; i++)
        {
            var currentList = selectList[i].List;
            for (var j=0; j < currentList.length; j++)
            {
                var listData = currentList[j]; 
                var text  = listData.Text;
                var value = listData.Value;

                if (copyTextAsValue != undefined && copyTextAsValue == true)
                    value = text;

                if (list.length == 0)
                    list = value + ":" + text;
                else
                    list += ";" + value + ":" + text;
            }
        }
    }
    return list;
}
function _loadSelectList(url, params, listId, onChangeFn)
{
    var onResponse = overloadFunction(_getSelectList_Response, listId, onChangeFn);
    _invoke(url, params, onResponse, false); /* call to _invoke method on AJAXHelper.js */
}
function _getSelectList_Response(listId, onChangeFn, data)
{
    var response = jQuery.parseJSON(data.d);
    if (response[responseResult])
    {
        //create list object based upon list data retrieved..
        var listData = response[responseValue];
        var listObject = new Object();
            listObject.ListId = listId;
            listObject.List = listData;

        //add list object to array of lists..
        _lists[_lists.length] = listObject;

        var selectedParentId = -1;
        var bindings = _getBindings();
        for (var i=0; i < bindings.length; i++)
        {
            var bindingList = bindings[i];
            for (var j=0; j < bindingList.length; j++)
            {
                var bindingListId = bindingList[j];
                if ( bindingListId.toLowerCase() == listId.toLowerCase() )
                {
                    if ( bindings[i][j-1] != undefined )
                    {
                        var parentBindingListId = bindingList[j-1];
                        selectedParentId = _getSelectedValueFromSelectList(parentBindingListId);
                        break;
                    }
                }
            }
        }

        //Find the selected Parent Id of the HTML Select List that needs to be filled..
        if (listData.length > 0)
        {
            //format object as "id:value;id:value;id:value"
            var currentList = "";

            if ( selectedParentId == -1 )
            {
                currentList = listData[0].List;
            }
            else
            {
                for(var i=0; i < listData.length; i++)
                {
                    if ( listData[i].Id == selectedParentId )
                    {
                        currentList = listData[i].List;
                        break;
                    }
                }
            }

            //var selectListData = _formatForSelectList(listData[0].List);
            var selectListData = _formatForSelectList(currentList);

            //fill HTML Select List with options..
            _fillSelectList(listId, selectListData);

            //bind HTML Select List's onChange event..
            _bindListOnChangeEvent(listId, onChangeFn);
        }
    }
}
function _bindListOnChangeEvent(listId, onChangeFn)
{
    var htmlSelect = $("#" + listId);
        htmlSelect.unbind('change');
        htmlSelect.change(function(event)
        {
            if (onChangeFn != undefined && onChangeFn != null & onChangeFn != "")
            {
                //var currentListId        = event.currentTarget.id;
                //var currentSelectedValue = event.currentTarget.value;
                onChangeFn.call(this);
            }
        });
}
function _setSelectListBasedOnSelection(selectedId, listId, cascadeActions)
{
    var currentList;    //list of listObject. Contains all lists, each identified by its own (parent) Id
    var targetList;     //listObject. Contains all elements of a listObject.

    //loop through all list objects inside lists array..
    for (var i = 0; i < _lists.length; i++)
    {
        var listObject = _lists[i];
        //find object with corresponding listId as its Id..
        if (listObject.ListId == listId)
        {
            currentList = listObject;
            break;
        }
    }

    //loop through all options inside current list..
    for (var i = 0; i < currentList.List.length; i++)
    {
        //find selected option on parent list to match with currentList.ListId..
        if (currentList.List[i].Id == selectedId)
        {
            targetList = currentList.List[i];
            break;
        }
    }

    if (targetList != undefined)
    {
        //format object as "id:value;id:value;id:value"
        var selectListData = _formatForSelectList(targetList.List);

        //fill HTML Select List with currentList's options..
        _fillSelectList(listId, selectListData);
    }
    else
    {
        //if no targetList was found, clear all existing items on listId..
        var selectList = $("#" + listId);
        _removeAllOptions(listId);
    }

    //if existing, run cascade actions..
    if (cascadeActions != undefined && cascadeActions != null && cascadeActions.length > 0)
    {
        for (var i = 0; i < cascadeActions.length; i++)
        {
            var action = cascadeActions[i];
                action.call(this);
        }
    }
}
function _disableOptionsFromSelectList(selectId, ids, enable)
{
    if (enable)
    {
        $("#" + selectId).children('option').attr("disabled", "disabled");
        for (var i = 0; i < ids.length; i++)
        {
            var optionValue = ids[i];
            $("#" + selectId + " option[value='" + optionValue + "']").removeAttr("disabled", "disabled");
        }
    }
    else
    {
        for (var i = 0; i < ids.length; i++)
        {
            var optionValue = ids[i];
            $("#" + selectId + " option[value='" + optionValue + "']").attr("disabled", "disabled");
        }
    }
}
function _getSelectedValueFromSelectList(listId)
{
    return $("#" + listId + " :selected").val();
}
function _getSelectedTextFromSelectList(listId)
{
    var selectedValue = _getSelectedValueFromSelectList(listId);
    return $("#" + listId + " option[value='" + selectedValue + "']").text();
}
function _getSelectLists()
{
    return _lists;
}
function _getSelectList(selectListId)
{
    var list = "";
    var lists = _getSelectLists();
    if ( lists.length > 0 )
    {
        for(var i=0; i < lists.length; i++)
        {
            if ( lists[i].ListId == selectListId )
            {
                list = lists[i].List;
                break;
            }
        }
    }    
    return list;
}

function _setBindings(list)
{
    var bindings = _getBindings();
        bindings[bindings.length] = list;
}
function _getBindings()
{
    return _bindings;
}

function _setSelectListBasedOnSelectionBindings(parentListId, selectedParentId, childListId, selectedChildId)
{
    var currentList;    //list of listObject. Contains all lists, each identified by its own (parent) Id
    var targetList;     //listObject. Contains all elements of a listObject.

    /* 1. Finds the lists which its Id corresponds to parentListId (this lists holds N list arrays, all belonging to same parentListId */
    for (var i = 0; i < _lists.length; i++)
    {
        var listObject = _lists[i];
        //find object with corresponding listId as its Id..
        if (listObject.ListId == parentListId)
        {
            currentList = listObject.List;
            break;
        }
    }

    /* 2. Look inside N arrays of currentList which is the list that corresponds to (parent) Id */
    for (var i = 0; i < currentList.length; i++)
    {
        //find selected option on parent list to match with currentList.ListId..
        if (currentList[i].Id == selectedParentId)
        {
            targetList = currentList[i].List;
            break;
        }
    }

    //3. Assign data options (pairs of value:text) of targetList to (target) HTML Select List..
    if (targetList != undefined)
    {
        //format object as "id:value;id:value;id:value"
        var selectListData = _formatForSelectList(targetList);

        //fill HTML Select List with currentList's options..
        _fillSelectList(childListId, selectListData);

        //set selectedChildId as selected on target list..
        if ( selectedChildId != undefined && selectedChildId != null && selectedChildId.length > 0 )
            $("#" + childListId).val(selectedChildId);
    }
    else
    {
        //if no targetList was found, clear all existing items on listId..
        var selectList = $("#" + childListId);
        _removeAllOptions(childListId);
    }

    return $("#" + childListId).val();
}
function _setSelectedIndex(selectListId, index)
{
    $("#" + selectListId)[0].selectedIndex = index;
}
function _setSelectedValue(selectListId, value)
{
    $("#" + selectListId).find("option[value=" + value + "]").attr("selected", true);
}
function _removeOption(selectListId, value)
{
    $("#" + selectListId).find("option[value=" + value + "]").remove();
}
function _removeAllOptions(selectListId)
{
    $("#" + selectListId).empty();
}
function _appendOption(selectListId, value, text, insertFirst, selected)
{
    var isSelected = (selected == true ? "selected='selected'" : "" );
    if ( insertFirst )
        $("#" + selectListId).prepend("<option value='" + value + "' " + isSelected + " >" + text + "</option>");
    else
        $("#" + selectListId).append("<option value='"  + value + "' " + isSelected + " >" + text + "</option>");
}
function _findOptionByText(selectListId, text)
{
    return $("#" + selectListId).find('option:contains('+ text +')');
}
function _findOptionByValue(selectListId, value)
{
    return $("#" + selectListId + " option[value='" + value + "']");
}
function _copyItems(sourceListId, targetListId)
{
    var sourceList = $("#" + sourceListId)[0];
    //var targetList = $("#" + targetListId);
    for (var i = 0; i < sourceList.options.length; i++) {
        var item = sourceList.options[i];
        Helpers.SelectListHelper.appendOption(targetListId, item.value, item.text);
    }
}